package com.binarycube.webserver.datasource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.binarycube.webserver.config.DatasourceConfig;
import com.binarycube.webserver.config.ParameterConfig;

public abstract class AbstractDataSource implements IDataSource {
	static Logger log = Logger.getLogger(AbstractDataSource.class.getName());
	
	protected List<Record> _records;
	protected DatasourceConfig _config;
	protected Map<String,Parameter> _params;
	
	
	
	@Override
	public void resetParams() {
		_params = new HashMap<String,Parameter>();
	}


	@Override
	public IDataSource setParam(String name, String value) {
		_params.put(name, new Parameter(name,value));
		return this;
	}
	
	/**
	 * Ensure the non-optional parameters are present, and have defaults set.
	 * Should always be called at the start of overriding classes implementation of doQuery()
	 * @return
	 */
	protected void validateParams() {
		for (ParameterConfig pc : _config.getParameters()){
			if (!_params.containsKey(pc.getName()) ) {
				_params.put(pc.getName(), new Parameter(pc.getName(), pc.getDefault(), pc.getType()) );
			}
		}
	}
	

	
	public void configure(DatasourceConfig config) {
		_config = config;
		_records = new ArrayList<Record>();
		resetParams();
	}

	/**
	 * Basic implementation of an iterator over the result set.
	 * @return
	 */
	public Iterator<Object> getIterator() {
		return new Iterator<Object>() {
			int counter = 0;
			
			@Override
			public boolean hasNext() {
				return counter < _records.size();
			}

			@Override
			public Object next() {
				return _records.get(counter++);
			}

			@Override
			public void remove() {
				//Not implemented
				
			}
		};
	}

	

}
